package com.zz.rabbitmq.simple;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DefaultConsumer;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class ConsumerDemo {
    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        // 1.建立连接
        ConnectionFactory factory = new ConnectionFactory();
        // 2.设置参数
        factory.setHost("8.140.201.46");
        factory.setPort(5672);
        factory.setVirtualHost("zz");
        factory.setUsername("admin");
        factory.setPassword("admin");
        Connection connection = factory.newConnection();
        // 3.创建 channel
        Channel channel = connection.createChannel();
        // 4.声明一个队列
        channel.queueDeclare("test001",true,false,false,null);
        // 5.消费消息
        DefaultConsumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, com.rabbitmq.client.Envelope envelope, com.rabbitmq.client.AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("接收到消息：" + new String(body));
            }
        };
        channel.basicConsume("test001",true,consumer);

        // 等待
        Thread.sleep(2000);
        // 6.关闭 channel
        channel.close();
        // 7.关闭连接
        connection.close();

    }
}
